package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.common.BaseContext;
import org.example.common.R;
import org.example.entity.AddressBook;
import org.example.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookContraller {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 获取用户地址list
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,currentId);
        queryWrapper.orderByDesc(AddressBook::getIsDefault).orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        addressBookService.save(addressBook);
        return R.success("新增地址成功");
    }


   @PutMapping("/default")
   public R<String> setDefault(@RequestBody AddressBook addressBook){
       Long id = addressBook.getId();
       //将原先默认地址设置为0
       LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
       queryWrapper.eq(AddressBook::getIsDefault,1);
       AddressBook OlderDefault = addressBookService.getOne(queryWrapper);
       if(OlderDefault!=null){
           OlderDefault.setIsDefault(0);
           addressBookService.updateById(OlderDefault);
       }

       AddressBook NewDefault = addressBookService.getById(id);
       NewDefault.setIsDefault(1);
       addressBookService.updateById(NewDefault);
       return R.success("默认地址设置成功");
    }

    @GetMapping("/default")
    public R<AddressBook> getDafault(){
        Long userid = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userid).eq(AddressBook::getIsDefault,1);
        AddressBook address = addressBookService.getOne(queryWrapper);
        return R.success(address);
    }
}
